package com.wwj.cloudpicturebackend.aop;

import com.wwj.cloudpicturebackend.annotation.AuthCheck;
import com.wwj.cloudpicturebackend.exception.BusinessException;
import com.wwj.cloudpicturebackend.exception.ErrorCode;
import com.wwj.cloudpicturebackend.model.domain.User;
import com.wwj.cloudpicturebackend.model.enums.UserRoleEnum;
import com.wwj.cloudpicturebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.filter.RequestContextFilter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;
    @Autowired
    private RequestContextFilter requestContextFilter;

    /**
     * 执行拦截
     *
     * @param joinPoint 切入点
     * @param authCheck 权限校验注解
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        String userRole = loginUser.getUserRole();
        //用户权限枚举值
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(userRole);
        //必须权限枚举值
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //不需要权限直接放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        //没有权限拒绝
        if(userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //要求必须有管理员权限，但用户没有管理员权限，拒绝
        if(UserRoleEnum.ADMIN.equals(mustRoleEnum)  && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //权限检验通过，放行
        return joinPoint.proceed();
    }
}
